<template>
  <section class='f-commission'>
    <section class="f-title">
      <van-tabs v-model:active="searchForm.incomeState" style="flex:1" color="#ffffff" background="#000000"
        title-active-color="#ffffff" title-inactive-color="#D8D8D8" @click-tab="clickTab">
        <van-tab title="已发放佣金" :name="2"></van-tab>
        <van-tab title="冻结佣金" :name="1"></van-tab>
      </van-tabs>
    </section>

    <ul class="f-search">
      <li class="g-flex-ct" style="width:180px" @click="openDatePicker()">
        <p class="f-mr-05">{{currentDateStr}}</p>
        <van-icon style="margin-top:2px" name="arrow-down" />
      </li>
      <li class="g-flex-ct" @click="openPicker(1)">
        <p class="f-mr-05">{{searchForm.incomeWayName || '全部类型'}}</p>
        <van-icon style="margin-top:2px" name="arrow-down" />
      </li>
    </ul>

    <p v-if="searchForm.incomeState == 2" class="f-count" style="color: #0D114E;">
      已发放 ¥{{toThousands(incomeStatics.incomeUnfreezentotal)}}
      （直接¥{{toThousands(incomeStatics.incomeUnfreezenTotalDirect)}}，间接¥{{toThousands(incomeStatics.incomeUnfreezenTotalIndidect)}}）
    </p>

    <p v-if="searchForm.incomeState == 1" class="f-count" style="color: #FF2424;">
      冻结佣金 ¥{{toThousands(incomeStatics.incomeFreezen)}}
      （直接 ¥{{toThousands(incomeStatics.incomeFreezenDirect)}}，间接¥{{toThousands(incomeStatics.incomeFreezenIndirect)}}）
    </p>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :style="{ height: currentHeight }" style="overflow-y: auto;">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <section class="f-cell-group" v-for="(item,index) in tableData" :key="index">
          <section class="f-cell">
            <div class="f-content">
              <img style="width:35px;height:35px" src="@/assets/icons/jhh_icon_datum.png" alt="">
              <ul style="margin-left:13px;">
                <li>
                  <p>售卡订单：</p>
                  <p class="f-tdu" style="color:#488BFE">{{item.businessOrderId}}</p>
                </li>
                <li>
                  <p>分佣时间：</p>
                  <p>{{getDateTime(item.createTime)[6]}}</p>
                </li>
                <li>
                  <p>佣金类别：</p>
                  <p>{{incomeWay[item.incomeWay]}}</p>
                </li>
                <li>
                  <p>关联商品：</p>
                  <p>{{item.goodsName}}</p>
                </li>
              </ul>
              <ul style="margin-top:16px;margin-left:24px;">
                <li>
                  <p>计划解冻：</p>
                  <p>{{getDateTime(item.unfreezeTime)[6]}}</p>
                </li>
                <li>
                  <p>佣金名称：</p>
                  <p>{{item.incomeName}}</p>
                </li>
                <li>
                  <p>佣金金额：</p>
                  <p>{{toThousands(item.income)}}</p>
                </li>
              </ul>
            </div>
            <p v-if="index+1 < tableData.length" class="f-divider"></p>
          </section>
        </section>
      </van-list>
    </van-pull-refresh>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">选择{{pickerTitle}}</p>
      <van-picker ref="pickerRef" v-model="searchForm.selectId" :columns="columns" :columns-field-names="customFieldName"
        :show-toolbar="false" />

      <div class="f-popup-btn">
        <van-button block type="primary" @click="handlePicker()">确定</van-button>
      </div>
    </van-popup>

    <Date-Picker ref="datePickerRef" @selectDate="selectDate"></Date-Picker>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, computed, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { toThousands, getUnixTime, initDatepicker, getDateTime } from '@/utils/utils';
import DatePicker from '../components/DatePicker.vue'
import api from '../api'

export default {
  components: { DatePicker },

  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const pickerRef = ref()
    const datePickerRef = ref()

    const state = reactive({
      searchForm: {
        "businessOrderId": "",
        "goodsId": "",
        "incomeOrderId": "",
        "incomeState": 2,
        "incomeWay": '',
        "orderBy": "id desc",
        "page": 1,
        "size": 10,
        "shopName": "",
        "timeMax": '',
        "timeMin": '',
        "timeType": 1
      },
      incomeWay: {
        '1': '直接',
        '2': '间接',
        '3': '月结',
      },

      currentDateStr: "",

      loading: false,
      finished: false,
      refreshing: false,
      tableData: [],
      total: 0,
      currentHeight: '740px',

      pickerTitle: '',
      showPicker: false,
      columns: [
        { text: '全部', value: '' },
        { text: '直接', value: '1' },
        { text: '间接', value: '2' },
        { text: '月结', value: '3' },
      ],
      customFieldName: {
        text: 'text',
        value: 'value',
        children: 'children'
      },

      incomeStatics: {},

      orderId: computed(() => {
        return store.state.orderId;
      }),
    })

    watch(() => state.orderId, (newVal, oldVal) => {
      state.searchForm.incomeWay = ''
      state.searchForm.incomeWayName = '全部类型'

      state.searchForm.businessOrderId = state.orderId
      state.refreshing = true
      onRefresh()
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '佣金订单',
        show: true,
        left: true,
        leftType: 'back',
        right: true,
        rightType: 'search',
      });

      state.currentHeight = window.innerHeight - 220 + 'px'

      state.searchForm.timeMin = initDatepicker(4, 3 * 30 * 24 * 60 * 60 * 1000);
      state.searchForm.timeMax = initDatepicker(3);
      let str = getDateTime(state.searchForm.timeMin)[8] + ' 至 ' + getDateTime(state.searchForm.timeMax)[8]
      state.currentDateStr = str

      state.searchForm.incomeState = Number(route.query.incomeState)
    })

    const onLoad = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))

      if (state.refreshing) {
        state.tableData = [];
        state.refreshing = false;
      }

      api.incomeList(json).then(res => {
        state.refreshing = false

        if (res.data.list.length) state.searchForm.page += 1
        state.tableData.push(...res.data.list)
        getIncomeListStatics()

        // 防止触发两次
        if (state.tableData.length >= res.data.total) {
          state.finished = true;
        } else {
          state.finished = false;
        }

        // 加载状态结束
        state.loading = false;

        // 数据全部加载完成
        if (state.tableData.length < 10) {
          state.finished = true;
        }
      }).catch(err => {
        state.loading = false;
        state.finished = true;
        state.refreshing = false
      })
    };

    const onRefresh = () => {
      state.searchForm.page = 1

      // 清空列表数据
      state.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      state.loading = true;
      onLoad();
    };

    const getIncomeListStatics = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))
      api.incomeListStatics(json).then(res => {
        state.incomeStatics = res.data
      })
    }

    const openDatePicker = () => {
      datePickerRef.value.datePopup = true
    }

    const selectDate = (e) => {
      let str = e.startStr + ' 至 ' + e.endStr
      state.currentDateStr = str
      state.searchForm.timeMin = getUnixTime(e.startStr)
      state.searchForm.timeMax = getUnixTime(e.endStr) - 999 + 24 * 60 * 60 * 1000;
      state.searchForm.timeType = e.timeType

      state.refreshing = true
      onRefresh()
    }

    const openPicker = (e) => {
      state.showPicker = true
    }

    const handlePicker = (e) => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      state.showPicker = false
      state.refreshing = true

      state.searchForm.incomeWay = data.value
      state.searchForm.incomeWayName = data.text == '全部' ? '' : data.text

      onRefresh()
    }

    const clickTab = (e) => {
      if (e.name == 1) {
        state.searchForm.incomeState = 1
      } else {
        state.searchForm.incomeState = 2
      }

      state.searchForm.incomeWay = ''
      state.searchForm.incomeWayName = '全部类型'
      state.refreshing = true
      onRefresh()
    }

    return {
      ...toRefs(state),
      getDateTime,
      pickerRef,
      datePickerRef,
      toThousands,
      onLoad,
      onRefresh,
      openDatePicker,
      selectDate,
      openPicker,
      handlePicker,
      clickTab
    }
  }
}
</script>
<style lang='scss' scoped>
.f-commission {
  .f-title {
    background: #000000;
    display: flex;
    align-items: center;
    padding-bottom: 8px;
  }
  .f-search {
    font-size: 12px;
    font-weight: 300;
    color: #000000;
    padding: 12px 15px 8px 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .f-count {
    font-weight: 300;
    font-size: 10px;
    padding-left: 14px;
    margin-bottom: 7px;
  }
  .f-cell-group {
    background: #ffffff;
    .f-cell {
      .f-content {
        display: flex;
        align-items: center;
        padding: 11px 0;
        padding-left: 11px;
        ul {
          li {
            font-size: 9px;
            color: #000000;
            display: flex;
            align-items: center;
            line-height: 16px;
            p:first-child {
              color: #666666;
            }
          }
        }
      }
      .f-divider {
        width: 100%;
        height: 1px;
        margin-left: 14px;
        border-bottom: 1px solid #dddddd;
      }
    }
  }
}
</style>